package com.example.logisticsingle.authorization;

import com.example.logisticsingle.Service.LoginService;
import com.example.logisticsingle.String.StringUtils;
import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.constants.ResponseEnum;
import com.example.logisticsingle.dto.Result;
import com.example.logisticsingle.entity.SSOUser;
import com.example.logisticsingle.model.LoginLog;
import com.example.logisticsingle.requsest.ClinetRequestInfo;
import com.example.logisticsingle.requsest.IPDetail;
import com.example.logisticsingle.requsest.RequestUtils;
import com.example.logisticsingle.utils.*;
import eu.bitwalker.useragentutils.DeviceType;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 登出处理

 *
 */
@Slf4j
@Data
@Component
public class SSOLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private LoginService loginService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        String token= SSOTokenLoginHelper.getTokenByRequest(request);
        boolean hasToken = SSOLoginStoreHelper.hasToken(token);
        SSOUser ssoUser = null;
        //记录日志
        LoginLog loginLog = null;
        String ip = request.getHeader(Config.REQUEST_IP);
        if(!hasToken) {
            log.error("Token不存在");
        }else {
            ssoUser = SSOLoginStoreHelper.get(token);
            SSOLoginStoreHelper.remove(token);
            loginLog = new LoginLog();
            loginLog.setUserName(ssoUser.getUsername());
            loginLog.setIpaddr(ip);
            loginLog.setLoginTime(new Date());
            loginLog.setMsg("退出登录");
            loginLog.setStatus("0");
        }



        String str = request.getHeader(Config.REQUEST_TYPE);
        String request_type = StringUtils.isNull(str)?request.getParameter(Config.REQUEST_TYPE):str;
        if(hasToken && StringUtils.isNotNull(request_type) && Integer.valueOf(request_type)==Config.REQUEST_TYPE_WEB) {
            ClinetRequestInfo clinetRequestInfo = RequestUtils.getClinetRequestInfo(request);
            if(null!=clinetRequestInfo) {
                loginLog.setBrowser(String.format("%s %s", clinetRequestInfo.getBrowserInfo().getName(),clinetRequestInfo.getBrowserVersion()));
                loginLog.setIpaddr(clinetRequestInfo.getIpInfo().getIp());
                loginLog.setLoginLocation(clinetRequestInfo.getIpInfo().getDesc());
                loginLog.setOs(clinetRequestInfo.getOsInfo().getName());
            }
            log.info("insert login log:{}",loginLog);
            loginService.insertLoginLog(loginLog);
            CookieUtil.remove(request, response, Config.SSO_SESSIONID);
            response.sendRedirect(request.getContextPath()+"/login");
        }else {
            if(hasToken) {
                String agent = request.getHeader(Config.REQUEST_USER_AGENT);
                agent = StringUtils.isNull(agent)?request.getHeader("User-Agent"):agent;
                ClinetRequestInfo clinetRequestInfo = RequestUtils.getClinetRequestInfo(agent,ip);
                if(null!=clinetRequestInfo) {
                    loginLog.setBrowser(String.format("%s %s", clinetRequestInfo.getBrowserInfo().getName(),clinetRequestInfo.getBrowserVersion()));
                    loginLog.setLoginLocation(clinetRequestInfo.getIpInfo().getDesc());
                    loginLog.setOs(clinetRequestInfo.getOsInfo().getName());
                    if(clinetRequestInfo.getDeviceType().equals(DeviceType.MOBILE.getName())) {
                        loginLog.setPhoneBrand(clinetRequestInfo.getMobileBrand());
                        loginLog.setPhoneModel(clinetRequestInfo.getMobileModel());
                        loginLog.setPhoneOs(clinetRequestInfo.getOsInfo().getName());
                    }
                }else {
                    IPDetail ipDetail = RequestUtils.getIpDetailInfo(ip);
                    if(null != ipDetail)
                        loginLog.setLoginLocation(ipDetail.getDesc());
                }
                log.info("insert login log:{}",loginLog);
                loginService.insertLoginLog(loginLog);
            }
            response.setStatus(HttpStatus.OK.value());
            response.setContentType("application/json;charset=UTF-8");
            Result<?> result = hasToken? ResultUtils.sucess(ResponseEnum.USER_LOGINOUT,ssoUser)
                    :ResultUtils.failure(ResponseEnum.TOKEN_INVALID);
            response.getWriter().write(JsonUtils.toJson(result));
        }
    }

}
